package juc;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程A、B、C，分别打印ABC，要求按顺序重复输出10次ABC
 */
public class SemaphoreLean {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(3, 3, 1,
                        TimeUnit.SECONDS, new ArrayBlockingQueue<>(3));
        Semaphore a = new Semaphore(1);
        Semaphore b = new Semaphore(0);
        Semaphore c = new Semaphore(0);
        threadPoolExecutor.execute(new PrintABC(a, 'A', b));
        threadPoolExecutor.execute(new PrintABC(b, 'B', c));
        threadPoolExecutor.execute(new PrintABC(c, 'C', a));
    }
}
class PrintABC implements Runnable {
    private Semaphore semaphore;
    private Semaphore nextSamaphore;
    private char objChar;
    public PrintABC(Semaphore samphone, char objChar, Semaphore nextSamaphore) {
        this.semaphore = samphone;
        this.objChar = objChar;
        this.nextSamaphore = nextSamaphore;
    }
    @Override
    public void run() {
        int i = 1;
        do {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(objChar);
            nextSamaphore.release();
            i++;
        } while (i < 11);
    }
}

class SemaphoneTest1 {
    static volatile int sum = 0;
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(0);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <=100 ; i++) {
                    sum+=i;
                }
                semaphore.release(1);
            }
        }).start();
        try {
            semaphore.acquire(1);// 如果没有信号量，当前执行这行代码的线程会被阻塞
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        semaphore.acquire(1);
        System.out.println(sum);
    }
}

class UserService {
    private static Semaphore semaphore = new Semaphore(10);
    // 当前这个方法只能最多被10个线程同时访问
    public void f() {
        try {
            semaphore.acquire(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName());
        semaphore.release(1);
    }
}
class Test10{
    public static void main(String[] args) {
        UserService userService = new UserService();
        for (int i = 0; i < 100 ; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    userService.f();
                }
            }).start();
        }
    }
}
